from django.core.management.base import BaseCommand
import tsl_backend.frontend_api.models.order_routing as order_routing
import json

class Command(BaseCommand):
    help = "Migrate end_weights to ActualWeight model"

    def add_arguments(self, parser):
        parser.add_argument("--migrate", type=str)

    
    def handle(self, *args, **options):
        print(options)
        if options["migrate"]=="weight":

            dispatcher_objs = order_routing.Dispatcher.objects.all()
            for obj in dispatcher_objs:

                route_detail_obj = obj.routedetail
                print(f"{route_detail_obj=}")
                end_weights = obj.end_weights
                if end_weights:
                    end_weights_json = json.loads(end_weights)
                    print(f"end_weights of {obj} is {end_weights_json} [{type(end_weights_json)}]")

                    for item in end_weights_json:
                        article = item["article"]
                        weight = item["weight"]
                        print(f"{article=} {weight=}")

                        actual_weight_obj, created = order_routing.ActualWeight.objects.update_or_create(actual_weight=weight, article=article, route_detail=route_detail_obj)
                        print(f"{actual_weight_obj=} {created=}")

            self.stdout.write(
                self.style.SUCCESS('Successfully to migrate weight to ActualWeight model')
            )
        else:
            print("--migrate=weight")


